//
// Created by 29108 on 2025/7/15.
//

#include "core_services/api_gateway/api_gateway.h"
#include "common/logger/logger.h"
#include "common/config/config_manager.h"
#include "common/http/http_client.h"
#include <chrono>
#include <future>
#include <sstream>
#include <algorithm>
#include <vector>
#include <nlohmann/json.hpp>

namespace core_services {
    namespace api_gateway {


        // ==================== Config静态方法实现 ====================

        /**
         * @brief 从ConfigManager加载API网关配置
         * @details 从配置管理器中读取各项配置参数，设置默认值
         * @return 完整的API网关配置对象
         */
        ApiGateway::Config ApiGateway::Config::fromConfigManager() {
            auto& config_manager = common::config::ConfigManager::getInstance();
            Config config;

            // HTTP服务器配置 - 基础网络参数
            config.server_config.host = config_manager.get<std::string>("api_gateway.server.host", "0.0.0.0");
            config.server_config.port = config_manager.get<int>("api_gateway.server.port", 8080);
            config.server_config.worker_threads = config_manager.get<int>("api_gateway.server.worker_threads", 8);
            config.server_config.max_request_size = config_manager.get<size_t>("api_gateway.server.max_request_size", 1048576);
            config.server_config.max_header_size = config_manager.get<size_t>("api_gateway.server.max_header_size", 8192);
            config.server_config.keep_alive_timeout_ms = config_manager.get<int>("api_gateway.server.keep_alive_timeout_ms", 60000);
            config.server_config.request_timeout_ms = config_manager.get<int>("api_gateway.server.request_timeout_ms", 30000);

            // 负载均衡策略配置
            std::string strategy = config_manager.get<std::string>("api_gateway.load_balancer.strategy", "round_robin");
            if (strategy == "weighted_round_robin") {
                config.load_balance_strategy = LoadBalancer::Strategy::WEIGHTED_ROUND_ROBIN;
            } else if (strategy == "least_connections") {
                config.load_balance_strategy = LoadBalancer::Strategy::LEAST_CONNECTIONS;
            } else {
                config.load_balance_strategy = LoadBalancer::Strategy::ROUND_ROBIN;
            }

            // 认证配置 - JWT相关设置
            config.enable_auth = config_manager.get<bool>("api_gateway.auth.enable", true);
            config.jwt_secret = config_manager.get<std::string>("api_gateway.auth.jwt_secret", "default_secret");
            config.jwt_expiry = std::chrono::seconds(config_manager.get<int>("api_gateway.auth.jwt_expiry_seconds", 3600));

            // 加载公开路径列表（无需认证的路径）
            auto public_paths_str = config_manager.get<std::string>("api_gateway.auth.public_paths", "/health,/metrics");
            std::stringstream ss(public_paths_str);
            std::string path;
            while (std::getline(ss, path, ',')) {
                if (!path.empty()) {
                    config.public_paths.push_back(path);
                }
            }

            // 监控配置
            config.enable_metrics = config_manager.get<bool>("api_gateway.monitoring.enable_metrics", true);
            config.enable_tracing = config_manager.get<bool>("api_gateway.monitoring.enable_tracing", true);
            config.metrics_path = config_manager.get<std::string>("api_gateway.monitoring.metrics_path", "/metrics");

            // CORS配置
            config.enable_cors = config_manager.get<bool>("api_gateway.cors.enable", true);

            // CORS允许的来源配置
            auto allowed_origins_str = config_manager.get<std::string>("api_gateway.cors.allowed_origins", "*");
            config.allowed_origins = parseStringList(allowed_origins_str);

            // CORS允许的HTTP方法配置
            auto allowed_methods_str = config_manager.get<std::string>("api_gateway.cors.allowed_methods",
                                                                      "GET,POST,PUT,DELETE,OPTIONS,HEAD,PATCH");
            config.allowed_methods = parseStringList(allowed_methods_str);

            // CORS允许的请求头配置
            auto allowed_headers_str = config_manager.get<std::string>("api_gateway.cors.allowed_headers",
                                                                      "Content-Type,Authorization,X-Requested-With,Accept,Origin");
            config.allowed_headers = parseStringList(allowed_headers_str);

            // 限流配置
            config.rate_limit_config = RateLimiter::Config::fromConfigManager();

            // 熔断器配置
            config.circuit_breaker_config = CircuitBreaker::Config::fromConfigManager();

            // 服务发现配置
            config.service_discovery_config.enable_service_discovery =
                config_manager.get<bool>("api_gateway.service_discovery.enable", true);
            config.service_discovery_config.health_check_interval =
                std::chrono::seconds(config_manager.get<int>("api_gateway.service_discovery.health_check_interval", 30));
            config.service_discovery_config.service_timeout =
                std::chrono::seconds(config_manager.get<int>("api_gateway.service_discovery.service_timeout", 120)); // 增加到120秒
            config.service_discovery_config.health_check_timeout_ms =
                config_manager.get<int>("api_gateway.service_discovery.health_check_timeout_ms", 5000);
            config.service_discovery_config.max_retry_count =
                config_manager.get<int>("api_gateway.service_discovery.max_retry_count", 3);
            config.service_discovery_config.auto_deregister_unhealthy =
                config_manager.get<bool>("api_gateway.service_discovery.auto_deregister_unhealthy", true);

            LOG_INFO("API网关配置加载完成 - 服务器: " + config.server_config.host + ":" +
                    std::to_string(config.server_config.port) +
                    ", 认证: " + (config.enable_auth ? "启用" : "禁用") +
                    ", CORS: " + (config.enable_cors ? "启用" : "禁用") +
                    ", 服务发现: " + (config.service_discovery_config.enable_service_discovery ? "启用" : "禁用"));
            return config;
        }

        /**
         * @brief 添加服务路由
         * @param route 路由配置
         */
        void ApiGateway::addServiceRoute(const ServiceRoute& route) {
            if (!route_manager_) {
                LOG_ERROR("RouteManager未初始化");
                return;
            }

            try {
                route_manager_->addRoute(route);
                LOG_INFO("添加服务路由: " + route.path_pattern + " -> " + route.service_name);
            } catch (const std::exception& e) {
                LOG_ERROR("添加服务路由失败: " + std::string(e.what()));
                throw;
            }
        }

        /**
         * @brief 注册服务实例
         * @param service_name 服务名称
         * @param instance 服务实例信息
         */
        void ApiGateway::registerServiceInstance(const std::string& service_name, const LoadBalancer::ServiceInstance& instance) {
            if (!load_balancer_) {
                LOG_ERROR("LoadBalancer未初始化");
                return;
            }

            try {
                load_balancer_->addInstance(service_name, instance);
                LOG_INFO("注册服务实例: " + service_name + " -> " + instance.host + ":" + std::to_string(instance.port));

                // 验证服务实例与路由配置的一致性
                validateServiceRegistration(service_name, instance);

            } catch (const std::exception& e) {
                LOG_ERROR("注册服务实例失败: " + std::string(e.what()));
                throw;
            }
        }

        /**
         * @brief 验证服务注册与路由配置的一致性
         * @param service_name 服务名称
         * @param instance 服务实例
         */
        void ApiGateway::validateServiceRegistration(const std::string& service_name, const LoadBalancer::ServiceInstance& instance) {
            if (!route_manager_) {
                LOG_WARNING("RouteManager未初始化，跳过路由验证");
                return;
            }

            // 查找该服务的路由配置
            auto routes = route_manager_->getRoutesByService(service_name);
            if (routes.empty()) {
                LOG_WARNING("服务 " + service_name + " 没有配置路由，请检查路由配置");
                return;
            }

            LOG_INFO("验证服务 " + service_name + " 的路由配置:");
            for (const auto& route : routes) {
                // 验证目标主机和端口是否匹配
                if (route.target_host == instance.host && route.target_port == instance.port) {
                    LOG_INFO("  ✓ 路由匹配: " + route.path_pattern + " -> " +
                            route.target_host + ":" + std::to_string(route.target_port));
                } else {
                    LOG_WARNING("  ⚠ 路由不匹配: " + route.path_pattern +
                               " 配置目标 " + route.target_host + ":" + std::to_string(route.target_port) +
                               " 但实例为 " + instance.host + ":" + std::to_string(instance.port));
                }
            }
        }

        /**
         * @brief 初始化HTTP服务器路由
         */
        void ApiGateway::setupHttpRoutes() {
            if (!http_server_) {
                LOG_ERROR("HttpServer未初始化");
                return;
            }

            try {
                // 设置健康检查路由（直接处理，不经过中间件）
                common::http::RequestHandler health_handler = [this](const common::http::HttpRequest& request, common::http::HttpResponse& response) {
                    LOG_DEBUG("处理健康检查请求: " + request.getPath());
                    handleHealthCheck(request, response);
                };
                http_server_->get("/health", health_handler);

                // 设置指标路由（直接处理，不经过中间件）
                if (config_.enable_metrics) {
                    common::http::RequestHandler metrics_handler = [this](const common::http::HttpRequest& request, common::http::HttpResponse& response) {
                        LOG_DEBUG("处理指标请求: " + request.getPath());
                        handleMetrics(request, response);
                    };
                    http_server_->get(config_.metrics_path, metrics_handler);
                }

                // 这是API网关的核心功能 - 处理所有API请求的路由转发
                common::http::RequestHandler api_handler = [this](const common::http::HttpRequest& request, common::http::HttpResponse& response) {
                    LOG_DEBUG("处理API请求: " + request.getMethodString() + " " + request.getPath());
                    handleRequest(request, response);
                };

                common::http::RequestHandler api_handler_all = [this](const common::http::HttpRequest& request, common::http::HttpResponse& response) {
                    LOG_DEBUG("处理API请求: " + request.getMethodString() + " " + request.getPath());
                    std::vector<std::string> routes = this->http_server_->getAllRoutes();
                    for (const auto& route : routes)
                    {
                        LOG_DEBUG(route);
                    }
                };

                // 注册通用路由处理器，处理所有API请求
                // 注册多种可能的API路径模式

                http_server_->post("/api/all", api_handler_all);
                // 1. 认证服务专用路由 - 高优先级
                // 注册认证服务的具体路由，确保正确处理
                http_server_->post("/api/v1/auth/register", api_handler);
                http_server_->post("/api/v1/auth/login", api_handler);
                http_server_->post("/api/v1/auth/logout", api_handler);
                http_server_->post("/api/v1/auth/refresh", api_handler);
                http_server_->get("/api/v1/auth/validate", api_handler);
                http_server_->options("/api/v1/auth/*", api_handler);

                // 游戏相关认证路由
                http_server_->post("/api/v1/game/login", api_handler);
                http_server_->get("/api/v1/game/servers", api_handler);
                http_server_->options("/api/v1/game/*", api_handler);

                // 2. 基础API路径：/api/* - 为每个HTTP方法单独注册
                http_server_->get("/api/*", api_handler);
                http_server_->post("/api/*", api_handler);
                http_server_->put("/api/*", api_handler);
                http_server_->del("/api/*", api_handler);
                http_server_->patch("/api/*", api_handler);
                http_server_->options("/api/*", api_handler);

                // 3. 版本化API路径：/api/v1/*, /api/v2/*
                http_server_->get("/api/v1/*", api_handler);
                http_server_->post("/api/v1/*", api_handler);
                http_server_->put("/api/v1/*", api_handler);
                http_server_->del("/api/v1/*", api_handler);
                http_server_->patch("/api/v1/*", api_handler);
                http_server_->options("/api/v1/*", api_handler);

                http_server_->get("/api/v2/*", api_handler);
                http_server_->post("/api/v2/*", api_handler);
                http_server_->put("/api/v2/*", api_handler);
                http_server_->del("/api/v2/*", api_handler);
                http_server_->patch("/api/v2/*", api_handler);
                http_server_->options("/api/v2/*", api_handler);

                // 4. 直接版本路径：/v1/*, /v2/*
                http_server_->get("/v1/*", api_handler);
                http_server_->post("/v1/*", api_handler);
                http_server_->put("/v1/*", api_handler);
                http_server_->del("/v1/*", api_handler);
                http_server_->patch("/v1/*", api_handler);
                http_server_->options("/v1/*", api_handler);

                http_server_->get("/v2/*", api_handler);
                http_server_->post("/v2/*", api_handler);
                http_server_->put("/v2/*", api_handler);
                http_server_->del("/v2/*", api_handler);
                http_server_->patch("/v2/*", api_handler);
                http_server_->options("/v2/*", api_handler);

                // 注册服务发现路由
                if (registry_handler_) {
                    registry_handler_->registerRoutes(http_server_.get());
                    LOG_INFO("服务发现路由注册完成");
                }

                LOG_DEBUG("认证服务专用路由注册完成:");
                LOG_DEBUG("  - POST /api/v1/auth/register (用户注册)");
                LOG_DEBUG("  - POST /api/v1/auth/login (用户登录)");
                LOG_DEBUG("  - POST /api/v1/auth/logout (用户登出)");
                LOG_DEBUG("  - POST /api/v1/auth/refresh (刷新令牌)");
                LOG_DEBUG("  - GET /api/v1/auth/validate (验证令牌)");
                LOG_DEBUG("  - POST /api/v1/game/login (游戏登录)");
                LOG_DEBUG("  - GET /api/v1/game/servers (游戏服务器列表)");

                LOG_INFO("通用API路由处理器设置完成 - 支持路径: /api/*, /api/v1/*, /api/v2/*, /v1/*, /v2/*");
                LOG_DEBUG("支持的HTTP方法: GET, POST, PUT, DELETE, PATCH, OPTIONS");

                // LOG_DEBUG("HTTP路由设置完成");
            } catch (const std::exception& e) {
                LOG_ERROR("设置HTTP路由失败: " + std::string(e.what()));
                throw;
            }
        }

        /**
         * @brief 初始化中间件
         */
        void ApiGateway::setupMiddleware() {
            if (!http_server_) {
                LOG_ERROR("HttpServer未初始化");
                return;
            }

            try {
                // 使用HttpServer的中间件系统
                setupCorsMiddleware();
                setupAuthMiddleware();
                setupRateLimitMiddleware();
                setupLoggingMiddleware();

                // 设置404处理器（处理未匹配的路由）
                common::http::RequestHandler not_found_handler = [this](const common::http::HttpRequest& request, common::http::HttpResponse& response) {
                    try {
                        // 处理404情况 - 未找到匹配的路由
                        LOG_WARNING("未找到匹配的路由: " + request.getMethodString() + " " + request.getPath());

                        // 记录404统计
                        stats_.not_found_requests++;

                        // 返回404响应
                        response.setStatus(404);
                        response.setHeader("Content-Type", "application/json");

                        nlohmann::json error_response;
                        error_response["error"] = "Not Found";
                        error_response["message"] = "The requested resource was not found";
                        error_response["path"] = request.getPath();
                        error_response["method"] = request.getMethodString();
                        error_response["timestamp"] = std::chrono::duration_cast<std::chrono::seconds>(
                            std::chrono::system_clock::now().time_since_epoch()).count();

                        response.setBody(error_response.dump(2));

                        // 记录请求完成日志（包含从中间件传递的开始时间）
                        logRequestCompletion(request, response);

                    } catch (const std::exception& e) {
                        LOG_ERROR("处理404请求时发生错误: " + std::string(e.what()));
                        response.setStatus(500);
                        response.setBody("Internal server error");
                    }
                };

                // 正确设置404处理器（只处理未匹配的路由）
                http_server_->setNotFoundHandler(not_found_handler);

                LOG_DEBUG("中间件设置完成");
            } catch (const std::exception& e) {
                LOG_ERROR("设置中间件失败: " + std::string(e.what()));
                throw;
            }
        }

        /**
         * @brief 解析逗号分隔的字符串列表
         * @param str 逗号分隔的字符串
         * @return 解析后的字符串向量
         *
         * @details 辅助函数，用于解析配置中的字符串列表
         * 自动去除前后空格，忽略空字符串
         */
        std::vector<std::string> ApiGateway::Config::parseStringList(const std::string& str) {
            std::vector<std::string> result;
            std::istringstream iss(str);
            std::string item;

            while (std::getline(iss, item, ',')) {
                // 去除前后空格
                item.erase(0, item.find_first_not_of(" \t\r\n"));
                item.erase(item.find_last_not_of(" \t\r\n") + 1);

                if (!item.empty()) {
                    result.push_back(item);
                }
            }

            return result;
        }

        /**
         * @brief 验证API网关配置的有效性
         * @details 检查各项配置参数是否合法，确保网关能正常启动
         * @return true表示配置有效，false表示配置无效
         */
        bool ApiGateway::Config::validate() const {
            // 验证HTTP服务器配置
            if (!server_config.validate()) {
                LOG_ERROR("HTTP服务器配置无效");
                return false;
            }

            // 验证JWT配置
            if (enable_auth) {
                if (jwt_secret.empty()) {
                    LOG_ERROR("启用认证时JWT密钥不能为空");
                    return false;
                }

                if (jwt_secret.length() < 32) {
                    LOG_WARNING("JWT密钥长度建议至少32位以确保安全性");
                }

                if (jwt_expiry.count() <= 0) {
                    LOG_ERROR("JWT过期时间必须大于0");
                    return false;
                }
            }

            // 验证监控配置
            if (enable_metrics && metrics_path.empty()) {
                LOG_ERROR("启用指标时指标路径不能为空");
                return false;
            }

            return true;
        }

        // ==================== ApiGateway主类实现 ====================

        /**
         * @brief API网关构造函数
         * @param config API网关配置对象
         * @details 初始化所有核心组件，包括HTTP服务器、路由管理器、负载均衡器、限流器、熔断器等
         * @throws std::invalid_argument 当配置无效时抛出异常
         */
        ApiGateway::ApiGateway(const Config& config)
            : config_(config) {

            // 验证配置有效性
            if (!config_.validate()) {
                throw std::invalid_argument("API网关配置无效");
            }

            LOG_INFO("正在初始化API网关...");

            try {
                // 初始化线程池 - 用于异步处理请求
                auto pool_config = common::thread_pool::ThreadPool::Config::fromConfigManager();
                pool_config.thread_name_prefix = "api-gateway-";
                thread_pool_ = std::make_shared<common::thread_pool::ThreadPool>(pool_config);

                // 初始化核心组件
                route_manager_ = std::make_unique<RouteManager>();
                load_balancer_ = std::make_shared<LoadBalancer>(config_.load_balance_strategy);
                rate_limiter_ = std::make_unique<RateLimiter>(config_.rate_limit_config);
                circuit_breaker_ = std::make_unique<CircuitBreaker>(config_.circuit_breaker_config);

                // 初始化服务发现组件
                service_discovery_ = std::make_shared<ServiceDiscovery>(config_.service_discovery_config, load_balancer_);
                registry_handler_ = std::make_unique<ServiceRegistryHandler>(service_discovery_);

                // 初始化HTTP服务器
                http_server_ = std::make_unique<common::http::HttpServer>(config_.server_config);

                // 设置路由和中间件
                setupHttpRoutes();
                setupMiddleware();

                // 初始化统计信息
                stats_.start_time = std::chrono::system_clock::now();

                LOG_INFO("API网关初始化完成");

            } catch (const std::exception& e) {
                LOG_ERROR("API网关初始化失败: " + std::string(e.what()));
                throw;
            }
        }

        /**
         * @brief API网关析构函数
         * @details 确保网关正确停止，释放所有资源
         */
        ApiGateway::~ApiGateway() {
            if (running_.load()) {
                stop();
            }
            LOG_INFO("API网关已销毁");
        }

        /**
         * @brief 启动API网关服务
         * @details 启动HTTP服务器，开始接收和处理请求
         * @throws std::runtime_error 当启动失败时抛出异常
         */
        void ApiGateway::start() {
            // 检查是否已经在运行
            if (running_.exchange(true)) {
                LOG_WARNING("API网关已经在运行中");
                return;
            }

            LOG_INFO("正在启动API网关...");

            try {
                // 启动服务发现
                if (service_discovery_) {
                    service_discovery_->start();
                    LOG_INFO("服务发现管理器启动成功");
                }

                // 启动HTTP服务器
                http_server_->start();

                LOG_INFO("API网关启动成功，监听地址: " + config_.server_config.host +
                        ":" + std::to_string(config_.server_config.port));

            } catch (const std::exception& e) {
                running_.store(false);
                LOG_ERROR("API网关启动失败: " + std::string(e.what()));
                throw;
            }
        }

        /**
         * @brief 停止API网关服务
         * @details 优雅地停止所有组件，确保正在处理的请求能够完成
         */
        void ApiGateway::stop() {
            if (!running_.exchange(false)) {
                LOG_WARNING("API网关未在运行");
                return;
            }

            LOG_INFO("正在停止API网关...");

            try {
                // 停止服务发现
                if (service_discovery_) {
                    service_discovery_->stop();
                    LOG_INFO("服务发现管理器已停止");
                }

                // 停止HTTP服务器
                if (http_server_) {
                    http_server_->stop();
                }

                // 停止线程池
                if (thread_pool_) {
                    thread_pool_->shutdown();
                }

                LOG_INFO("API网关已停止");

            } catch (const std::exception& e) {
                LOG_ERROR("停止API网关时发生错误: " + std::string(e.what()));
            }
        }

        /**
         * @brief 检查API网关是否正在运行
         * @return true表示正在运行，false表示已停止
         */
        bool ApiGateway::isRunning() const {
            return running_.load();
        }

        /**
         * @brief 处理HTTP请求（核心业务逻辑）
         * @param request HTTP请求
         * @param response HTTP响应
         */
        void ApiGateway::handleRequest(const common::http::HttpRequest& request, common::http::HttpResponse& response) {
            // 更新统计信息
            stats_.total_requests++;

            // 提取客户端信息
            std::string client_ip = request.getClientIP();

            // 记录访问日志
            // LOG_DEBUG("处理请求: " + request.getMethodString() + " " + request.getPath() + " from " + client_ip);

            // 查找匹配的路由
            LOG_DEBUG("开始查找路由: method=" + request.getMethodString() + ", path=" + request.getPath());
            LOG_DEBUG("当前路由总数: " + std::to_string(route_manager_->getRouteCount()));

            auto route = route_manager_->findRoute(request.getMethodString(), request.getPath());
            if (!route) {
                LOG_WARNING("未找到匹配的路由: " + request.getMethodString() + " " + request.getPath());

                // 添加详细的调试信息
                LOG_DEBUG("所有已注册的路由:");
                auto all_routes = route_manager_->getAllRoutes();
                if (all_routes.empty()) {
                    LOG_DEBUG("  - 没有已注册的路由");
                } else {
                    for (const auto& route_info : all_routes) {
                        std::string methods_str = "[";
                        for (size_t i = 0; i < route_info.methods.size(); ++i) {
                            if (i > 0) methods_str += ",";
                            methods_str += route_info.methods[i];
                        }
                        methods_str += "]";

                        std::string route_str = route_info.service_name + " " + methods_str + " " +
                                              route_info.path_pattern + " -> " +
                                              route_info.target_host + ":" + std::to_string(route_info.target_port);
                        LOG_DEBUG("  - " + route_str);
                    }
                }

                response.setStatus(404);
                response.setBody("Route not found");
                stats_.not_found_requests++;
                return;
            }

            LOG_DEBUG("找到匹配路由: " + route->service_name + " -> " + route->path_pattern);

            // 检查熔断器状态
            // 注意：CircuitBreaker没有allowRequest方法，我们简化处理
            if (circuit_breaker_) {
                // 这里可以添加熔断器逻辑，暂时跳过
                // LOG_DEBUG("熔断器检查: " + route->service_name);
            }

            // 选择服务实例
            auto instance = load_balancer_->selectInstance(route->service_name);
            if (!instance.has_value()) {
                response.setStatus(503);
                response.setBody("No available service instances");
                stats_.no_instance_errors++;
                return;
            }

            // 转发请求到目标服务
            forwardRequest(*route, instance.value(), request, response);

            // 记录成功统计
            stats_.successful_requests++;

            // 记录请求完成日志
            logRequestCompletion(request, response);
        }

        /**
         * @brief 处理健康检查请求
         * @param request HTTP请求
         * @param response HTTP响应
         */
        void ApiGateway::handleHealthCheck(const common::http::HttpRequest& request, common::http::HttpResponse& response) {
            LOG_DEBUG("处理健康检查请求");
            try {
                // 检查各组件健康状态
                bool healthy = true;
                std::string status = "OK";

                // 检查HTTP服务器
                if (!http_server_ || !isRunning()) {
                    healthy = false;
                    status = "HTTP server not running";
                }

                // 检查路由管理器（移除getRouteCount调用以避免死锁）
                if (healthy && !route_manager_) {
                    healthy = false;
                    status = "Route manager not initialized";
                }

                // 构建健康检查响应
                nlohmann::json health_response;
                health_response["status"] = healthy ? "UP" : "DOWN";
                health_response["message"] = status;
                health_response["timestamp"] = std::chrono::duration_cast<std::chrono::seconds>(
                    std::chrono::system_clock::now().time_since_epoch()).count();
                health_response["version"] = "1.0.0";

                // 添加组件状态
                health_response["components"]["http_server"] = http_server_ ? "UP" : "DOWN";
                health_response["components"]["route_manager"] = route_manager_ ? "UP" : "DOWN";
                health_response["components"]["load_balancer"] = load_balancer_ ? "UP" : "DOWN";
                health_response["components"]["rate_limiter"] = rate_limiter_ ? "UP" : "DOWN";
                health_response["components"]["circuit_breaker"] = circuit_breaker_ ? "UP" : "DOWN";

                // 添加异步发送支持标识
                health_response["async_response"] = true;
                health_response["response_method"] = "async";

                response.setStatus(healthy ? 200 : 503);
                response.setHeader("Content-Type", "application/json");
                response.setBody(health_response.dump(2));

                LOG_DEBUG("健康检查响应已设置，状态: " + std::to_string(healthy ? 200 : 503));

                // 记录请求完成日志
                logRequestCompletion(request, response);

            } catch (const std::exception& e) {
                LOG_ERROR("健康检查时发生错误: " + std::string(e.what()));
                response.setStatus(500);
                response.setBody("{\"status\":\"ERROR\",\"message\":\"Health check failed\"}");

                // 记录错误请求完成日志
                logRequestCompletion(request, response);
            }
        }

        /**
         * @brief 处理指标请求
         * @param request HTTP请求
         * @param response HTTP响应
         */
        void ApiGateway::handleMetrics(const common::http::HttpRequest& request, common::http::HttpResponse& response) {
            try {
                std::ostringstream metrics;

                // 基础指标
                metrics << "# HELP api_gateway_requests_total Total number of requests\n";
                metrics << "# TYPE api_gateway_requests_total counter\n";
                metrics << "api_gateway_requests_total " << stats_.total_requests << "\n\n";

                metrics << "# HELP api_gateway_successful_requests_total Total number of successful requests\n";
                metrics << "# TYPE api_gateway_successful_requests_total counter\n";
                metrics << "api_gateway_successful_requests_total " << stats_.successful_requests << "\n\n";

                metrics << "# HELP api_gateway_error_requests_total Total number of error requests\n";
                metrics << "# TYPE api_gateway_error_requests_total counter\n";
                metrics << "api_gateway_error_requests_total " << stats_.error_requests << "\n\n";

                metrics << "# HELP api_gateway_not_found_requests_total Total number of not found requests\n";
                metrics << "# TYPE api_gateway_not_found_requests_total counter\n";
                metrics << "api_gateway_not_found_requests_total " << stats_.not_found_requests << "\n\n";

                // 平均响应时间
                double avg_response_time = stats_.total_requests > 0 ?
                    static_cast<double>(stats_.total_response_time) / stats_.total_requests : 0.0;
                metrics << "# HELP api_gateway_avg_response_time_ms Average response time in milliseconds\n";
                metrics << "# TYPE api_gateway_avg_response_time_ms gauge\n";
                metrics << "api_gateway_avg_response_time_ms " << avg_response_time << "\n\n";

                // 熔断器指标
                metrics << "# HELP api_gateway_circuit_breaker_rejections_total Total circuit breaker rejections\n";
                metrics << "# TYPE api_gateway_circuit_breaker_rejections_total counter\n";
                metrics << "api_gateway_circuit_breaker_rejections_total " << stats_.circuit_breaker_rejections << "\n\n";

                // 异步响应指标
                metrics << "# HELP api_gateway_async_responses_total Total async responses sent\n";
                metrics << "# TYPE api_gateway_async_responses_total counter\n";
                metrics << "api_gateway_async_responses_total 1\n\n";

                response.setStatus(200);
                response.setHeader("Content-Type", "text/plain");
                response.setHeader("X-Response-Method", "async");
                response.setBody(metrics.str());

                // 记录请求完成日志
                logRequestCompletion(request, response);

            } catch (const std::exception& e) {
                LOG_ERROR("获取指标时发生错误: " + std::string(e.what()));
                response.setStatus(500);
                response.setBody("Failed to get metrics");

                // 记录错误请求完成日志
                logRequestCompletion(request, response);
            }
        }

        /**
         * @brief 应用CORS头部
         * @param request HTTP请求
         * @param response HTTP响应
         */
        void ApiGateway::applyCorsHeaders(const common::http::HttpRequest& request, common::http::HttpResponse& response) {
            // 设置允许的来源
            std::string origin = request.getHeader("Origin");
            if (!origin.empty() && isOriginAllowed(origin)) {
                response.setHeader("Access-Control-Allow-Origin", origin);
            } else if (config_.allowed_origins.size() == 1 && config_.allowed_origins[0] == "*") {
                response.setHeader("Access-Control-Allow-Origin", "*");
            }

            // 设置允许的方法
            std::string allowed_methods;
            for (size_t i = 0; i < config_.allowed_methods.size(); ++i) {
                if (i > 0) allowed_methods += ", ";
                allowed_methods += config_.allowed_methods[i];
            }
            response.setHeader("Access-Control-Allow-Methods", allowed_methods);

            // 设置允许的头部
            std::string allowed_headers;
            for (size_t i = 0; i < config_.allowed_headers.size(); ++i) {
                if (i > 0) allowed_headers += ", ";
                allowed_headers += config_.allowed_headers[i];
            }
            response.setHeader("Access-Control-Allow-Headers", allowed_headers);

            // 设置其他CORS头部
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Max-Age", "86400");
        }

        /**
         * @brief 认证请求
         * @param request HTTP请求
         * @param response HTTP响应
         * @return true表示认证通过
         */
        bool ApiGateway::authenticateRequest(const common::http::HttpRequest& request, common::http::HttpResponse& response) {
            try {
                // 检查是否为公开路径
                std::string path = request.getPath();
                for (const auto& public_path : config_.public_paths) {
                    if (path.find(public_path) == 0) {
                        return true; // 公开路径，无需认证
                    }
                }

                // 提取Authorization头
                std::string auth_header = request.getHeader("Authorization");
                if (auth_header.empty()) {
                    response.setStatus(401);
                    response.setBody("Missing authorization header");
                    return false;
                }

                // 检查Bearer token格式
                if (auth_header.find("Bearer ") != 0) {
                    response.setStatus(401);
                    response.setBody("Invalid authorization format");
                    return false;
                }

                // 提取token
                std::string token = auth_header.substr(7);
                if (token.empty()) {
                    response.setStatus(401);
                    response.setBody("Empty token");
                    return false;
                }

                // 验证JWT token（简化实现）
                if (!validateJwtToken(token)) {
                    response.setStatus(401);
                    response.setBody("Invalid token");
                    return false;
                }

                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("认证请求时发生错误: " + std::string(e.what()));
                response.setStatus(500);
                response.setBody("Authentication error");
                return false;
            }
        }

        /**
         * @brief 检查限流
         * @param request HTTP请求
         * @param response HTTP响应
         * @return true表示通过限流检查
         */
        bool ApiGateway::checkRateLimit(const common::http::HttpRequest& request, common::http::HttpResponse& response) {
            if (!rate_limiter_) {
                return true; // 如果没有限流器，直接通过
            }

            try {
                std::string client_ip = request.getClientIP();
                std::string api_path = request.getPath();

                bool allowed = rate_limiter_->allowRequest(client_ip, api_path);
                if (!allowed) {
                    response.setStatus(429);
                    response.setHeader("X-RateLimit-Limit", "100");
                    response.setHeader("X-RateLimit-Remaining", "0");
                    response.setHeader("Retry-After", "60");
                    response.setBody("Rate limit exceeded");

                    stats_.rate_limit_rejections++;
                    return false;
                }

                return true;

            } catch (const std::exception& e) {
                LOG_ERROR("检查限流时发生错误: " + std::string(e.what()));
                // 限流检查出错时，为了安全起见，拒绝请求
                response.setStatus(503);
                response.setBody("Rate limit check failed");
                return false;
            }
        }

        /**
         * @brief 转发请求到目标服务
         * @param route 路由配置
         * @param instance 服务实例
         * @param request 原始请求
         * @param response 响应对象
         */
        void ApiGateway::forwardRequest(const ServiceRoute& route, const LoadBalancer::ServiceInstance& instance,
                                       const common::http::HttpRequest& request, common::http::HttpResponse& response) {
            try {
                // 构建目标URL
                std::string target_url = "http://" + instance.host + ":" + std::to_string(instance.port);

                // 处理路径转换
                std::string target_path = request.getPath();
                if (route.strip_path_prefix && !route.path_pattern.empty()) {
                    // 移除匹配的路径前缀
                    if (target_path.find(route.path_pattern) == 0) {
                        target_path = target_path.substr(route.path_pattern.length());
                    }
                }

                // 添加目标路径前缀
                if (!route.target_path_prefix.empty()) {
                    target_path = route.target_path_prefix + target_path;
                }

                target_url += target_path;

                // 创建HTTP客户端并发送请求
                LOG_DEBUG("转发请求到: " + target_url);

                common::http::HttpClient client;
                common::http::HttpClientResponse client_response;

                // 根据HTTP方法发送请求
                std::string method = request.getMethodString();
                LOG_INFO("=== 开始发送HTTP请求 ===");
                LOG_INFO("目标URL: " + target_url);
                LOG_INFO("HTTP方法: " + method);
                LOG_INFO("超时时间: " + std::to_string(route.timeout_ms) + "ms");
                LOG_INFO("请求体大小: " + std::to_string(request.getBody().length()) + " bytes");

                if (method == "GET") {
                    LOG_DEBUG("发送GET请求");
                    client_response = client.get(target_url, route.timeout_ms);
                } else if (method == "POST") {
                    // 复制原始请求的头部
                    std::unordered_map<std::string, std::string> forward_headers;
                    forward_headers["Content-Type"] = request.getHeader("Content-Type");
                    if (request.hasHeader("Authorization")) {
                        forward_headers["Authorization"] = request.getHeader("Authorization");
                        LOG_DEBUG("转发Authorization头部");
                    }

                    LOG_DEBUG("发送POST请求，请求体: " + request.getBody().substr(0, 200) + (request.getBody().length() > 200 ? "..." : ""));
                    LOG_DEBUG("转发头部数量: " + std::to_string(forward_headers.size()));

                    client_response = client.post(target_url, request.getBody(), forward_headers, route.timeout_ms);
                } else if (method == "PUT") {
                    std::unordered_map<std::string, std::string> forward_headers;
                    forward_headers["Content-Type"] = request.getHeader("Content-Type");
                    if (request.hasHeader("Authorization")) {
                        forward_headers["Authorization"] = request.getHeader("Authorization");
                    }
                    LOG_DEBUG("发送PUT请求");
                    client_response = client.put(target_url, request.getBody(), forward_headers, route.timeout_ms);
                } else if (method == "DELETE") {
                    LOG_DEBUG("发送DELETE请求");
                    client_response = client.del(target_url, route.timeout_ms);
                } else {
                    LOG_ERROR("不支持的HTTP方法: " + method);
                    response.setStatus(405);
                    response.setBody("Method not allowed");
                    return;
                }

                LOG_INFO("HTTP请求发送完成，开始处理响应...");

                // 检查客户端响应
                if (client_response.success) {
                    LOG_INFO("请求转发成功: 状态码=" + std::to_string(client_response.status_code));
                    LOG_DEBUG("响应体: " + client_response.body.substr(0, 200) + (client_response.body.length() > 200 ? "..." : ""));

                    // 转发成功，复制响应（包括错误响应）
                    response.setStatus(client_response.status_code);
                    response.setBody(client_response.body);

                    // 复制重要的响应头
                    for (const auto& [key, value] : client_response.headers) {
                        if (key == "Content-Type" || key == "Content-Length" ||
                            key.find("X-") == 0) {  // 复制自定义头部
                            response.setHeader(key, value);
                        }
                    }

                    // 记录成功转发（即使是错误响应也算转发成功）
                    if (circuit_breaker_) {
                        circuit_breaker_->recordSuccess();
                    }
                } else {
                    // 检查是否是HTTP错误响应（有状态码但不是2xx）
                    if (client_response.status_code > 0) {
                        LOG_WARNING("收到HTTP错误响应: 状态码=" + std::to_string(client_response.status_code));
                        LOG_DEBUG("错误响应体: " + client_response.body.substr(0, 200) + (client_response.body.length() > 200 ? "..." : ""));

                        // 这是业务层面的错误，直接转发给客户端
                        response.setStatus(client_response.status_code);
                        response.setBody(client_response.body);

                        // 复制响应头
                        for (const auto& [key, value] : client_response.headers) {
                            if (key == "Content-Type" || key == "Content-Length") {
                                response.setHeader(key, value);
                            }
                        }

                        // 业务错误也算转发成功
                        if (circuit_breaker_) {
                            circuit_breaker_->recordSuccess();
                        }
                    } else {
                        // 网络层面的转发失败（连接失败、超时等）
                        LOG_ERROR("网络转发失败: " + client_response.error_message);

                        response.setStatus(502);
                        response.setHeader("Content-Type", "application/json");
                        response.setBody("{\"error\":{\"code\":\"BAD_GATEWAY\",\"message\":\"Failed to forward request: " +
                                       client_response.error_message + "\"},\"success\":false}");

                        // 记录失败
                        if (circuit_breaker_) {
                            std::exception_ptr eptr = std::make_exception_ptr(std::runtime_error(client_response.error_message));
                            circuit_breaker_->recordFailure(eptr);
                        }
                    }
                }

            } catch (const std::exception& e) {
                LOG_ERROR("转发请求时发生错误: " + std::string(e.what()));
                response.setStatus(502);
                response.setBody("Bad gateway");

                // 记录失败
                if (circuit_breaker_) {
                    std::exception_ptr eptr = std::current_exception();
                    circuit_breaker_->recordFailure(eptr);
                }
            }
        }

        /**
         * @brief 检查来源是否被允许
         * @param origin 请求来源
         * @return true表示允许
         */
        bool ApiGateway::isOriginAllowed(const std::string& origin) const {
            for (const auto& allowed_origin : config_.allowed_origins) {
                if (allowed_origin == "*" || allowed_origin == origin) {
                    return true;
                }
            }
            return false;
        }

        /**
         * @brief 验证JWT token
         * @param token JWT token
         * @return true表示有效
         */
        bool ApiGateway::validateJwtToken(const std::string& token) const {
            // 简化的JWT验证实现
            // 实际项目中应该使用专门的JWT库进行验证
            if (token.empty() || token.length() < 10) {
                return false;
            }

            // 检查token格式（简化检查）
            size_t first_dot = token.find('.');
            size_t second_dot = token.find('.', first_dot + 1);

            if (first_dot == std::string::npos || second_dot == std::string::npos) {
                return false; // JWT应该有两个点分隔三部分
            }

            // 这里应该验证签名、过期时间等
            // 简化实现：只要格式正确就认为有效
            return true;
        }

        /**
         * @brief 设置CORS中间件
         */
        void ApiGateway::setupCorsMiddleware() {
            if (!config_.enable_cors) {
                return;
            }

            // 使用HttpServer的中间件系统添加CORS中间件
            common::http::MiddlewareHandler cors_middleware = [this](const common::http::HttpRequest& request, common::http::HttpResponse& response) {
                // 应用CORS头部
                applyCorsHeaders(request, response);

                // 处理OPTIONS预检请求
                if (request.getMethod() == common::http::HttpMethod::OPTIONS) {
                    response.setStatus(200);
                    response.setBody("");
                    return false; // 停止执行后续中间件
                }

                return true; // 继续执行下一个中间件
            };

            http_server_->use(cors_middleware);
            LOG_DEBUG("CORS中间件设置完成");

        }

        /**
         * @brief 设置认证中间件
         */
        void ApiGateway::setupAuthMiddleware() {
            if (!config_.enable_auth) {
                return;
            }

            // 使用HttpServer的中间件系统添加认证中间件
            common::http::MiddlewareHandler auth_middleware = [this](const common::http::HttpRequest& request, common::http::HttpResponse& response) {
                // 跳过健康检查和指标路径的认证
                std::string path = request.getPath();
                if (path == "/health" || path == config_.metrics_path) {
                    return true; // 跳过认证，继续执行
                }

                if (!authenticateRequest(request, response)) {
                    return false; // 认证失败，停止执行
                }

                return true; // 认证成功，继续执行
            };

            http_server_->use(auth_middleware);
            LOG_DEBUG("认证中间件设置完成");

        }

        /**
         * @brief 设置限流中间件
         */
        void ApiGateway::setupRateLimitMiddleware() {
            if (!rate_limiter_) {
                return;
            }

            // 使用HttpServer的中间件系统添加限流中间件
            common::http::MiddlewareHandler rate_limit_middleware = [this](const common::http::HttpRequest& request, common::http::HttpResponse& response) {
                // 跳过健康检查和指标路径的限流
                std::string path = request.getPath();
                if (path == "/health" || path == config_.metrics_path) {
                    return true; // 跳过限流，继续执行
                }

                if (!checkRateLimit(request, response)) {
                    return false; // 限流，停止执行
                }

                return true; // 通过限流，继续执行
            };

            http_server_->use(rate_limit_middleware);
            LOG_DEBUG("限流中间件设置完成");

        }

        /**
         * @brief 设置日志中间件
         */
        void ApiGateway::setupLoggingMiddleware() {
            // 使用HttpServer的中间件系统添加日志中间件
            common::http::MiddlewareHandler logging_middleware = [this](const common::http::HttpRequest& request, common::http::HttpResponse& response) {
                auto start_time = std::chrono::steady_clock::now();

                // 注意：在MiddlewareHandler中，我们无法直接控制下一个中间件的执行
                // HttpServer会自动处理中间件链的执行
                // 这里我们只记录请求开始时间，响应时间将在请求处理完成后记录

                // 将开始时间存储在响应的自定义头部中（用于后续计算）
                response.setHeader("X-Request-Start-Time", std::to_string(
                    std::chrono::duration_cast<std::chrono::microseconds>(
                        start_time.time_since_epoch()).count()));

                LOG_DEBUG("Request started: " + request.getMethodString() + " " + request.getPath());

                return true; // 继续执行下一个中间件
            };

            http_server_->use(logging_middleware);
            // LOG_DEBUG("日志中间件设置完成");
        }

        /**
         * @brief 记录请求完成日志
         */
        void ApiGateway::logRequestCompletion(const common::http::HttpRequest& request, const common::http::HttpResponse& response) {
            try {
                // 尝试从响应头中获取开始时间
                std::string start_time_str = response.getHeader("X-Request-Start-Time");
                if (!start_time_str.empty()) {
                    auto start_time_us = std::stoull(start_time_str);
                    auto start_time = std::chrono::time_point<std::chrono::steady_clock>(
                        std::chrono::microseconds(start_time_us));

                    auto end_time = std::chrono::steady_clock::now();
                    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);

                    LOG_DEBUG("Request completed: " + request.getMethodString() + " " + request.getPath() +
                            " - Status: " + std::to_string(response.getStatus()) +
                            " - Duration: " + std::to_string(duration.count()) + "ms");
                } else {
                    // 如果没有开始时间，只记录基本信息
                    LOG_DEBUG("Request completed: " + request.getMethodString() + " " + request.getPath() +
                            " - Status: " + std::to_string(response.getStatus()));
                }
            } catch (const std::exception& e) {
                LOG_ERROR("记录请求完成日志时发生错误: " + std::string(e.what()));
            }
        }

        /**
         * @brief 获取所有路由
         * @return 路由列表
         */
        std::vector<ServiceRoute> ApiGateway::getAllRoutes() const {
            if (!route_manager_) {
                LOG_WARNING("RouteManager未初始化");
                return {};
            }
            return route_manager_->getAllRoutes();
        }

        /**
         * @brief 查找匹配的路由（用于测试）
         * @param method HTTP方法
         * @param path 请求路径
         * @return 匹配的路由，如果没有找到则返回nullptr
         */
        std::shared_ptr<ServiceRoute> ApiGateway::findRoute(const std::string& method, const std::string& path) const {
            if (!route_manager_) {
                LOG_WARNING("RouteManager未初始化");
                return nullptr;
            }
            return route_manager_->findRoute(method, path);
        }

    }
}